package com.example.activitidemo.server;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

@Service
public class ActivitiService {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    /**
     * start activiti process
     *
     * @return instance id
     */
    public String start(String taskType,String businessId, Map<String,Object> params) {
        ProcessDefinitionQuery createProcessDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        ProcessDefinitionQuery deploymentId = createProcessDefinitionQuery.deploymentId(taskType);
        ProcessInstance instance = runtimeService.startProcessInstanceById(deploymentId.singleResult().getId(),businessId,params);
        return instance.getId();
    }
    /**
     * get user task list
     *
     * @param uid
     * @return user task list
     */
    public List<Task> getTask(String uid) {
        List<Task> tasks = taskService
                .createTaskQuery()
                .taskAssignee(uid)
                .list();
        return tasks;
    }

    public String deploy(String name, InputStream inputStream){
        String deployId = repositoryService.createDeployment()
                .addInputStream(name, inputStream)
                .name(name)
                .key(name)
                .deploy().getId();
        return deployId;
    }

    public String complete(String taskId,Map<String,Object> params){
        taskService.complete(taskId,params);
        return "success";
    }
}